<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-24 16:38:30
 * @LastEditTime: 2024-06-28 16:57:25
 * @FilePath: \project\src\views\product\trademark\index.vue
-->
<template>
  <div>
    <el-card>
      <el-button type="primary" icon="plus" @click="hAdd">添加品牌</el-button>
      <el-table border :data="trademarkList" style="margin: 10px 0">
        <el-table-column prop="id" label="序号" width="80" align="center"/>
        <el-table-column prop="tmName" label="品牌名称" width="180" />
        <el-table-column prop="logoUrl" label="品牌LOGO">
          <template #="{row}">
            <img :src="row.logoUrl" alt="未加载图片" style="width: 100px;height: 100px;">
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="120">
          <template #="{row}">
            <el-button icon="edit" size="small" @click="hEdit(row)"></el-button>
            <el-popconfirm
              width="220"
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="InfoFilled"
              :title="`确认删除${row.tmName}这个品牌吗?`"
              @confirm="hDelete(row.id)"
            >
              <template #reference>
                <el-button icon="delete" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 10]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="hsizeChange"
        @current-change="getrademarkList"
      />
    </el-card>

    <!-- 添加？修改 -->
    <el-dialog 
      v-model="editVisible" 
      :title="isEdit?'修改品牌':'添加品牌'" 
      width="500"
      :before-close="hClose"
    >
      <el-form ref="formRef" :model="trademarkForm" :rules="rules" label-width="100px" style="width: 80%;">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input 
            v-model="trademarkForm.tmName"
            autocomplete="off"
            placeholder="请输入品牌名称"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="hLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="trademarkForm.logoUrl" :src="trademarkForm.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { reqTrademarkList, reqAddEditTrademark, reqDeleteTrademark } from '@/api/product/trademark';
import { Records, TradeMarkRespones, TradeMark } from '@/api/product/trademark/type';
import { ElMessage } from 'element-plus';
import type { UploadProps } from 'element-plus';

let currentPage = ref<number>(1)
let limit = ref<number>(3)
let total = ref<number>(0)
let trademarkList = ref<Records>([])
let editVisible = ref<boolean>(false)
let isEdit = ref<boolean>(false)
let trademarkForm = reactive<TradeMark>({
  tmName: '', 
  logoUrl: '',
})
let formRef = ref() // form组件实例

// 获取 - 品牌数据
let getrademarkList = async (pager=1)=>{
  currentPage.value = pager
  const res:TradeMarkRespones = await reqTrademarkList(currentPage.value, limit.value)
  if(res.code != 200) return
  total.value = res.data.total
  trademarkList.value = res.data.records
}
let hsizeChange = ()=>{
  getrademarkList()
}
onMounted(() => {
  getrademarkList()
})

// 校验rules
const validTmNAme = (rule: any, value: any, callback: any) => {
  if(value.length>=2){
    callback()
  } else {
    callback(new Error('品牌名称位数需要大于两位'))
  }
}
const validLogoUrl = (rule: any, value: any, callback: any) => {
  if(value){
    callback()
  } else {
    callback(new Error('请上传LOGO图'))
  }
}
const rules = {
  tmName: [{required: true, trigger: 'blur', validator: validTmNAme}],
  logoUrl: [{required: true, validator: validLogoUrl}],
}

// 添加
let hAdd = ()=>{
  trademarkForm.id = 0
  trademarkForm.tmName = ''
  trademarkForm.logoUrl = ''
  isEdit.value = false
  editVisible.value = true
}
// 修改
let hEdit = (row:TradeMark)=>{
  isEdit.value = true
  editVisible.value = true
  trademarkForm.tmName = row.tmName
  trademarkForm.logoUrl = row.logoUrl
  trademarkForm.id = row.id
}
// 删除
let hDelete = async (id:number)=>{
  const res = await reqDeleteTrademark(id)
  if(res.code != 200) return ElMessage({type: 'error',message:'删除品牌失败'+res.data})
  ElMessage({
    type: 'success',
    message:'删除品牌成功！'
  })
  getrademarkList(trademarkList.value.length?currentPage.value:currentPage.value-1)
}
// 弹窗 - 确认
let confirm = async ()=>{
  await formRef.value.validate()
  const res:any = await reqAddEditTrademark(trademarkForm)
  
  if(res.code != 200) {
    return ElMessage({
      type: 'error',
      message:isEdit.value?'修改品牌失败！':'添加品牌失败！'+res.data
    })
  }
  ElMessage({
    type: 'success',
    message:isEdit.value?'修改品牌成功！':'添加品牌成功！'
  })
  getrademarkList(isEdit.value?currentPage.value:1)
  editVisible.value = false
}
// 弹窗关闭 - 前
let hClose = (done: () => void) =>{
  formRef.value?.resetFields()
  done()
}

// 图片上传 - 前
const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
    ElMessage({
      type: 'error',
      message:'上传文件务必是PNG|JPG|GIF'
    })
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage({
      type: 'error',
      message:'上传文件大小应小于 4M'
    })
    return false
  }
  return true
}
// 图片上传 - 成功
const hLogoSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  // response: 服务器返回的数据
  trademarkForm.logoUrl = response.data
  formRef.value.clearValidate('logoUrl') // 清除校验
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
